from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
from modules import user, admin, video, pay, api
from utils import captcha
import uuid

# # 通过参数禁用所有文档
# app = FastAPI(
#     title="视频解析平台",
#     docs_url=None,        # 关闭 Swagger UI 文档（/docs）
#     redoc_url=None,       # 关闭 ReDoc 文档（/redoc）
#     openapi_url=None      # 关闭 OpenAPI 规范文件（/openapi.json），这是文档的数据源
# )

app = FastAPI(title="视频解析平台")

# session 用于保存登录状态
app.add_middleware(SessionMiddleware, secret_key="secret_session_key")

# # 配置 Session 中间件，设置过期时间（例如：3600秒 = 1小时）
# app.add_middleware(
#     SessionMiddleware,
#     secret_key=str(uuid.uuid4()),  # 生产环境需使用随机安全的密钥
#     max_age=3600  # Session 有效期，超时自动失效
# )

# 挂载模块路由
app.include_router(user.router)
app.include_router(admin.router)
app.include_router(video.router)
app.include_router(pay.router)
app.include_router(captcha.router)
app.include_router(api.router)

# 静态文件支持
app.mount("/static", StaticFiles(directory="static"), name="static")

from fastapi import Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
templates = Jinja2Templates(directory="templates")

# 首页路由
@app.get("/", response_class=HTMLResponse)
def index(request: Request):
    # 登录时会有，否则 None
    user = request.session.get("user")
    print(user)

    return templates.TemplateResponse("index.html", {
        "request": request,
        "user": user
    })


from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import RedirectResponse, JSONResponse

# 捕获404异常并跳转到自定义页面
@app.exception_handler(StarletteHTTPException)
async def custom_404_handler(request: Request, exc: StarletteHTTPException):
    if exc.status_code == 404:
        # 跳转到自定义404页面
        return RedirectResponse(url="/")

    if exc.status_code == 301:
        return JSONResponse(
            status_code=exc.status_code,
            content={"code": exc.status_code, "msg": exc.detail}
        )

    # 对于其他HTTP异常，使用默认处理方式
    # return await app.default_exception_handler(request, exc)
    # return JSONResponse(
    #     status_code=exc.status_code,
    #     content={"detail": exc.detail}  # FastAPI默认HTTP异常的返回格式
    # )
    return RedirectResponse(url="/")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)